var express = require('express');
var db = require('../db.js')
var router = express.Router()
var bodyParser = require('body-parser');
var urlencodedParser = bodyParser.urlencoded({ extended: false })

//获取订单信息
router.get('/list', async function (req, res) {
    let { currentPage=1, pagesize=5, order = 'id', by = 'asc', keyword } = req.query
    let sql = `select m.id, m.orderDetail,m.orderTime,m.total,m.status from inquiry as m`
    let sqla = `select count(*) as total from inquiry as p`
    if (keyword) {
        sql += `  where m.orderTime like '%${keyword}%'`
        sqla += ` where p.orderTime like '%${keyword}%'`
    }
    if (order) {
        sql += ` order by m.${order} ${by}`
    }
    console.log(sql)
    sql += ` limit ${currentPage * pagesize},${pagesize}`
    let p1 = await db.doSql(sql)
    let p2 = await db.doSql(sqla)
    res.send(db.hand(p1, p2[0].total))
})

// 新增
router.post('/addList', urlencodedParser, async function (req, res) {
    var quiry = req.body
    var sql = `insert into inquiry (orderDetail, orderTime, total, status) values ('${quiry.orderDetail}',"${quiry.orderTime}","${quiry.total}","${quiry.status}")`
    // console.log(sql)
    const r = await db.doSql(sql)
    res.send(db.addData(r))
})

// 删除
router.get('/delList', async function (req, res) {
    var { id } = req.query
    console.log(id);
    let sql = `delete from inquiry where id in(${id})`;
    let r = await db.doSql(sql)
    res.send(db.deleteData(r))
})

// 修改
router.post('/updateList', urlencodedParser, async function (req, res) {
    var {
        id,
        orderDetail,
        orderTime,
        total,
        status
    } = req.body;
    var sql = `update inquiry set orderDetail='${orderDetail}',orderTime="${orderTime}",total='${total}',status='${status}' where id='${id}'`
    const data = await db.doSql(sql)
    res.send(db.updateData(data))
})

module.exports = router